/*******************************************************************************
    文件名称： 
	开发者：孙磊
	开发时间地点：2013.12.8 于郑州
	邮箱：zhongyuansunlei@163.com
	版本信息：
	需要完善的地方，部分javascript 会导致筛选url不精准
		
********************************************************************************/
#include <string.h>
#include <stdio.h>
#include "queue.h"
#include "common.h"
#include "strutil.h"
#include "html.h"
#include "log.h"


#define TAG_A				"A"
#define TAG_IMAGE  	"IMG"
#define TAG_SCRIPT	"SCRIPT"
#define TAG_LINK  	"LINK"

#define ATTRI_HREF	"href"
#define ATTRI_SRC		"src"


#define CHARACTOR(p,num)	*(p+num)


// 这个只获取前tag, 返回tag长度
int iget_tag_name(char* psrc)
{
	char* p, *q;
	p = psrc;
	
	q = strstr(p, " ");
	if(q) { // 说明有空格
		vstr_upper(p, q - p);
		return (q - p);
	}	
	
	return strlen(p);
}

int iget_url_from_tag(char* psrc, char* ptagatrri, queue *pq, int (*mem_alloc_cp_func)(queue_elem*, void*))
{
	char* p, *q, *r;
	int irtn;
	
	p = psrc;
	
	if((q = strstr(p, ptagatrri)) == NULL) {
		return 0;
	}
	
	p = q + 1;
	if((q = strstr(p, "\"")) == NULL) {
		return 0;
	}
	
	r = q + 1;
	p = r;
	if((q = strstr(p, "\"")) == NULL) {
		return 0;
	}
	*q = '\0';
	
	
	irtn = icheck_url(r);
	if(irtn == -1)
		return 0;
	
	
	return ien_queue(pq, r+irtn, mem_alloc_cp_func);
}


int iparse_tag(char* psrc, queue *pq, int (*mem_alloc_cp_func)(queue_elem*, void*))
{
	char *q = psrc + 1; // 因为传递过来的就是<ABC....>
	iget_tag_name(q);
	if(!strncmp(q, TAG_IMAGE, strlen(TAG_IMAGE))) {
		return iget_url_from_tag(psrc, ATTRI_SRC, pq, mem_alloc_cp_func);
	} else if(!strncmp(q, TAG_SCRIPT, strlen(TAG_SCRIPT))) {
		return iget_url_from_tag(psrc, ATTRI_SRC, pq, mem_alloc_cp_func);
	} else if(!strncmp(q, TAG_LINK, strlen(TAG_LINK))) {
		return iget_url_from_tag(psrc, ATTRI_HREF, pq, mem_alloc_cp_func);
	} else if(!strncmp(q, TAG_A, strlen(TAG_A))) {
		return iget_url_from_tag(psrc, ATTRI_HREF, pq, mem_alloc_cp_func);
	} else 
		return 0;
}

int iparser_html(char* phtml, queue *pq, int (*mem_alloc_cp_func)(queue_elem*, void*))
{
	char * p, *q;
	p = phtml;
	int irtn;
	//int i = 0;
	
	while(p=strstr(p, "<")) {
		//Trace("i = %d\n", i);
		//i++;
		if((CHARACTOR(p,1) == '!') || (CHARACTOR(p,1) == '/')) { // 注释或者doctype 或者标签结束
			p = p + 1;
			continue;
		}
		
		if((q=strstr(p, ">")) == NULL) {
			p = q + 1;
			continue;
		} 
		
		*q = '\0';
	//	Trace("p = %s\n", p);
		irtn = iparse_tag(p, pq, mem_alloc_cp_func);
		if(irtn == RC_NOSPACE)
			return RC_NOSPACE;
		p = q + 1;
	}
	
	return 0;
}
